package com.qf.java2201.securitydemo1.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.java2201.securitydemo1.mapper.UsersMapper;
import com.qf.java2201.securitydemo1.pojo.Menu;
import com.qf.java2201.securitydemo1.pojo.Role;
import com.qf.java2201.securitydemo1.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @date 2022/5/16
 * @desc
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;


    // 得到 正确的  用户信息，  然后 在比较密码是否正确
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //在这里写   根据用户名 查询数据库

        //设置角色，角色的概念在之后章节介绍
        //List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //可以从数据库获取用户名和密码   这里返回的是数据库中的数据    是 存储的正确数据
        //return new User("qfAdmin",new BCryptPasswordEncoder().encode("123456"),auths);

        //这里返回的用户中 包含了  数据库中正确的 用户信息
        //然后 再跟用户登录传过来的 密码 进行比对



        //认证 查询数据库
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUsername,username);

        Users users = usersMapper.selectOne(wrapper);
        if(users==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //权限集合
        //List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("admin");

        //从数据库  查询

        //查询角色
        List<Role> roles = usersMapper.selectRoleByUserId(users.getId());
        //查询权限
        List<Menu> menus = usersMapper.selectMenuByUserId(users.getId());

        //auths 存放的是 当前用户 拥有的  角色和 权限
        List<GrantedAuthority> auths = new ArrayList<>();

        for(Role role:roles){
            // 遍历查询出来的角色   把角色封装到  GrantedAuthority 对象中
            auths.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }

        for(Menu menu:menus){
            auths.add(new SimpleGrantedAuthority(menu.getPermission()));
        }

        return new User(users.getUsername(),users.getPassword(),auths);
    }
}
